package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    //处理新增员工用户名重复的异常
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'wzc' for key 'employee.idx_username'

        log.info("新增用户的用户名已存在");
        //将异常信息取出来，处理后返回给界面
        String s = ex.getMessage();

        if(s.contains("Duplicate entry")){     //重复键值对
            String[] split = s.split(" ");
            String username = split[2];    //取用户名

            return Result.error(username+ MessageConstant.ALREADY_EXISTS);
        }else {
            //未知错误
            return Result.error((MessageConstant.UNKNOWN_ERROR));
        }

    }

}
